﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace Adnc.Infra.Helper
{
    public class ReturnData
    {
        public int code { get; set; }

        public string issuccess { get; set; }

        public string msg { get; set; }
    }

    public class SignData
    {
        public string Sign { get; set; }

        public long Time { get; set; }
    }

    public static class RequestHelp
    {
        /// <summary>
        /// 合作方编号
        /// </summary>
        public static string PartnerId = "";

        /// <summary>
        /// 接入密钥
        /// </summary>
        public static string PartnerKey = "";

        /// <summary>
        /// 授权码
        /// </summary>
        public static string Token = "";

        /// <summary>
        /// api地址
        /// </summary>
        public static string Api = "";

        /// <summary>
        /// 签名计算
        /// </summary>
        /// <returns></returns>
        private static SignData Sign(string method)
        {
            var time = (DateTime.Now.Ticks - 621356256000000000) / 10000000;
            var sign_str = $"{method}{PartnerId}token{Token}ts{time}{PartnerKey}";

            using var md5 = MD5.Create();
            var result = md5.ComputeHash(Encoding.UTF8.GetBytes(sign_str));
            var strResult = BitConverter.ToString(result);
            var sign = strResult.Replace("-", "").ToLower();
            return new SignData() { Sign = sign, Time = time };
        }

        public static T Post<T>(string method, object obj)
        {
            var si = Sign(method);
            var url = $"{Api}?method={method}&partnerid={PartnerId}&token={Token}&ts={si.Time}&sign={si.Sign}";

            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.Accept = "application/json";
            request.ContentType = "application/json; charset=utf-8";
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            var data = JsonConvert.SerializeObject(obj, timeConverter);
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
                var result = reader.ReadToEnd();
                return JsonConvert.DeserializeObject<T>(result);
        }
    }
}
